<template>
  <departmentBase>
    <template v-slot:main-left>
      <SearchTrees
        ref="SearchTrees"
        :lazy="lazy"
        :treeData="treeData"
        :defaultProps="defaultProps"
        @getlazyLoad="lazyLoad"
        @deleteHandle="deleteHandle"
        @handleNodeClickTree="handleNodeClickTree"
      />
    </template>
    <!-- 右侧部分 -->
    <template v-slot:search-info>
      <searchMain
        size="mini"
        ref="searchMain"
        :model="formData"
        :itemList="formItemList"
        :searchBtn="searchBtn"
      />
    </template>
    <template v-slot:table-main>
      <div class="depForm" ref="depForm">
        <el-form
          :model="depForm"
          ref="depRuleForm"
          label-width="auto"
          class="demo-ruleForm"
          :rules="rules"
        >
          <div class="top">
            <el-form-item label="上级科室" prop="parentId">
              <template>
                <treeselect
                  style="width: 100%"
                  :disabled="showKeShi"
                  :options="treeSelectData"
                  :load-options="loadOptions"
                  clearable
                  placeholder="请选择科室名称"
                  v-model="depForm.parentId"
                >
                </treeselect>
              </template>
            </el-form-item>
            <el-form-item
              v-for="item in ItemList"
              :key="item.prop"
              :label="item.label"
              :prop="item.prop"
            >
              <el-input
                v-if="item.type === 'Input'"
                v-model="depForm[item.prop]"
                :disabled="formEdit"
                :placeholder="item.placeholder"
              />
              <el-select
                v-if="item.type === 'Select'"
                v-model="depForm[item.prop]"
                :style="{ width: '100%' }"
                :disabled="formEdit"
                :placeholder="item.placeholder"
              >
                <el-option
                  v-for="op in item.options"
                  :key="op.value"
                  :label="op.label"
                  :value="op.value"
                />
              </el-select>
              <el-select
                v-if="item.type === 'entryCodeType'"
                v-model="depForm[item.prop]"
                :disabled="formEdit"
                :placeholder="item.placeholder"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="op in item.options"
                  :key="op.entryCode"
                  :label="op.entryValue"
                  :value="op.entryCode"
                />
              </el-select>
              <el-select
                v-if="item.type === 'basicIdType'"
                v-model="depForm[item.prop]"
                :disabled="formEdit"
                :placeholder="item.placeholder"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="op in item.options"
                  :key="op.entryCode"
                  :label="op.entryValue"
                  :value="op.entryCode"
                />
              </el-select>
              <el-radio-group
                v-if="item.type === 'Radio'"
                v-model="depForm[item.prop]"
                :disabled="formEdit"
              >
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="bottom">
            <el-form-item>
              <el-button
                :disabled="formEdit"
                type="primary"
                @click="formStatus === 'create' ? create() : update()"
                >确定</el-button
              >
              <el-button :disabled="formEdit" @click="cancel">取消</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </template>
  </departmentBase>
</template>
<script>
import departmentBase from "@/components/Layout/departmentBase.vue"
import SearchTrees from "@/components/Trees/SearchTrees.vue"
import searchMain from "@/components/CommonForm/form-item/DepartmentForm.vue"
import { addressList, dataProps } from "@/simdata/healthData.js"
import Treeselect from "@riophae/vue-treeselect"
// import the styles
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { validatenull } from "@/utils/validate"
import {
  tree,
  list,
  getById,
  editDeptDic,
  addDeptDic,
  Delete,
  medicalStaffList,
  LazyTree,
  deptDicLazyTree
} from "@/api/setup/standard-department.js"
import { entryCodeType, basicIdType } from "@/simdata/healthData.js"
import success from "@/utils/operation-message.js"
const defaultDic = {
  hisDeptDicId: undefined,
  code: undefined, // 科室编码
  name: undefined, // 科室名称
  abbreviation: undefined, // 简称
  parentId: undefined, // 上级科室
  grade: undefined, // 级别编码
  property: undefined, // 科室性质
  type: undefined, // 科室类别
  administerType: null, // 管理类别
  director: undefined,
  deputyDirector: undefined,
  status: 1, // 是否启用
  remark: undefined // 描述
}
export default {
  components: {
    departmentBase,
    SearchTrees,
    searchMain,
    Treeselect
  },
  data() {
    return {
      // 配置表单按钮
      searchBtn: [
        {
          label: "搜索",
          icon: "el-icon-search",
          type: "primary",
          disabled: false,
          handle: () => this.searchHandle()
        },
        {
          label: "新增",
          icon: "el-icon-circle-plus-outline",
          type: "primary",
          disabled: false,
          handle: () => this.handleCreate()
        }
      ],
      formData: {
        //查询条件
        label: undefined, // 关键字
        parentId: undefined
      },
      formStatus: "", // 控制是新增还是修改
      addStatus: false, // 控制搜索按钮
      isGetNode: true, // 控制按钮
      // 控制禁用状态
      formEdit: true,
      // 树的数据
      treeData: [
        {
          abbreviation: null,
          children: [
            {
              abbreviation: null,
              children: null,
              code: null,
              createBy: null,
              createTime: null,
              departmentTypeList: null,
              deptCategory: null,
              deptCategoryList: null,
              deputyDirector: null,
              director: null,
              grade: null,
              hasChildrenId: null,
              hisDeptDicId: null,
              id: "DD856A246FF44489B951E74D8502221F",
              isCopy: null,
              isLeaf: true,
              label: "职业卫生监督科",
              lastUpdateBy: null,
              lastUpdateTime: null,
              orgName: null,
              parentId: "09E79FE3387042EBA48DC4611F253992",
              property: null,
              remark: null,
              status: null,
              sysOrganizationId: null,
              type: null
            }
          ],
          code: null,
          hasChildrenId: "E302FAA644E840799B75D0486CFB8603",
          hisDeptDicId: null,
          id: "09E79FE3387042EBA48DC4611F253992",
          isCopy: null,
          isLeaf: null,
          label: "卫生监督机构业务科室分类与代码",
          lastUpdateBy: null,
          lastUpdateTime: null,
          orgName: null,
          parentId: "-1",
          property: null,
          remark: null,
          status: null,
          sysOrganizationId: null,
          type: null
        }
      ],
      defaultProps: {
        // 配置树显示节点
        id: "id",
        children: "children",
        label: "label",
        isLeaf: "isLeaf"
      },
      showKeShi: true,
      treeSelectData: [], // 上级科室
      lazy: true, // 默认加载
      formItemList: [
        {
          type: "Input",
          label: "",
          prop: "label",
          span: 6,
          placeholder: "科室名称"
        }
      ],
      doctorOptions: [], // 医护
      // 提交表单的字段
      depForm: Object.assign({}, defaultDic),
      // 验证字段
      rules: {
        code: [{ required: true, message: "请输入科室编码", trigger: "blur" }],
        name: [{ required: true, message: "请输入科室名称", trigger: "blur" }]
      },
      // 配置显示的提交表单
      ItemList: [
        {
          type: "Input",
          label: "科室编码",
          prop: "code",
          disabled: true,
          placeholder: "请输入科室编码"
        },
        {
          type: "Input",
          label: "科室名称",
          prop: "name",
          disabled: true,
          placeholder: "请输入名称"
        },
        {
          type: "Input",
          label: "简称",
          prop: "abbreviation",
          disabled: true,
          placeholder: "请输入简称"
        },
        {
          type: "Input",
          label: "级别编码",
          prop: "grade",
          disabled: true,
          placeholder: "请输入简称"
        },
        {
          type: "basicIdType",
          label: "科室性质",
          prop: "property",
          options: basicIdType,
          disabled: true,
          placeholder: "请选择科室性质"
        },
        {
          type: "entryCodeType",
          label: "科室类别",
          prop: "type",
          options: entryCodeType,
          disabled: true,
          placeholder: "请选择科室类别"
        },
        {
          type: "Select",
          label: "管理类别",
          prop: "administerType",
          options: [
            { label: "全部", value: 1 },
            { label: "公卫", value: 2 },
            { label: "医疗", value: 3 }
          ],
          disabled: true,
          placeholder: "请选择管理类别"
        },
        {
          type: "Radio",
          label: "是否启用",
          prop: "status",
          options: [],
          disabled: true,
          placeholder: ""
        },
        {
          type: "Input",
          label: "描述",
          prop: "remark",
          disabled: true,
          placeholder: "请输入描述"
        }
      ],
      // 查询医护信息字段
      doctorList: {
        sysOrgId: undefined,
        deptId: undefined
      },
      userInfo: JSON.parse(window.sessionStorage.getItem("userInfo")),
      // 设置默认参数
      // userInfo: {
      //   sysOrganizationId: "1001"
      // },
      // 默认设置
      userHisDeptId: null
    }
  },
  methods: {
    //科室树查询
    async getMenuList() {
      if (validatenull(this.formData.label)) {
        this.formData.parentId = "-1"
      } else {
        this.lazy = false
        this.formData.parentId = ""
      }
      const res = await LazyTree(this.formData)
      console.log(res)
      if (res.code === "1000") {
        this.treeData = res.data
      }
    },
    // 加载数据
    async lazyLoad(node, resolve) {
      console.log(node)
      if (node.level === 0) {
        if (validatenull(this.formData.label)) {
          this.formData.parentId = "-1"
        } else {
          this.formData.parentId = ""
        }
        const res = await LazyTree(this.formData)
        console.log(res)
        if (res.code === "1000") {
          this.treeData = res.data
          return resolve(this.treeData)
        }
      }
      if (node.level > 0) {
        console.log(node)
        const result = await deptDicLazyTree(
          node.data.id,
          this.userInfo.sysOrganizationId
        )
        if (result.code === "1000") {
          return resolve(result.data)
        }
      }
    },
    // 点击树回显
    async handleNodeClickTree(data) {
      if (this.isGetNode) {
        this.formStatus = "update"
        this.formEdit = false
        //查询医护人员
        this.doctorList.sysOrgId = this.userInfo.sysOrganizationId
        this.doctorList.deptId = this.userHisDeptId
        const res = await medicalStaffList(this.doctorList)

        if (res.code === "1000") {
          this.doctorOptions = res.data
        }
        let params = {
          id: data.parentId
        }
        //上级科室
        const result = await LazyTree(params)

        if (result.code === "1000") {
          let Data = result.data
          this.treeSelectData = []
          this.treeSelectData.push({
            id: "-1",
            label: "顶级菜单",
            children: Data
          })
        }
        // 根据id查询科室基础字典
        const resA = await getById(data.id)
        // console.log(resA)
        if (resA.code === "1000") {
          let result = resA.data
          // 科室性质与科室类别不为null时转为字符串，result中返回number，下拉框的value为string
          result.property =
            result.property != null ? "" + result.property : null
          result.type = result.type != null ? "" + result.type : null
          if (result.type == 5) {
            this.addStatus = true
          } else {
            this.addStatus = false
          }
          this.depForm = result
        }
      }
    },

    // 上级机构下拉树
    async loadOptions({ action, parentNode, callback }) {
      if (parentNode.isLeaf) {
        parentNode.children = 0
        callback()
      } else {
        if (parentNode.id) {
          const res = await deptDicLazyTree(
            parentNode.id,
            this.userInfo.sysOrganizationId
          )
          console.log(res)
          if (res.code === "1000") {
            parentNode.children = res.data
            callback()
          }
        }
      }
    },
    // 修改
    update() {
      this.formEdit = true
      this.$refs.depRuleForm.validate(async valid => {
        if (!valid) {
          this.formEdit = false
          return false
        } else {
          const res = await editDeptDic(this.depForm)
          // console.log(res)
          if (res.code === "1000") {
            this.formEdit = false
            this.cancel()
            this.getMenuList()
            success()
          }
        }
      })
    },
    // 点击搜索按钮
    searchHandle() {
      this.getMenuList()
    },
    // 点击新增按钮
    async handleCreate() {
      let orgDeptdata = this.$refs.SearchTrees.$refs.treeList.getCurrentNode()
      console.log(orgDeptdata)
      if (orgDeptdata === null || orgDeptdata === undefined) {
        this.resetForm()
        this.treeSelectData.push({ id: "-1", label: "顶级菜单", children: [] })
        this.depForm.parentId = "-1"
        this.exeBeforeCreate()
      } else {
        this.resetForm()
        let params = {
          id: orgDeptdata.id
        }
        const res = await LazyTree(params)
        if (res.code === "1000") {
          this.treeSelectData = []
          this.treeSelectData = res.data
          this.depForm.parentId = orgDeptdata.id
        }
        this.exeBeforeCreate()
      }
    },
    // 医护
    async exeBeforeCreate() {
      this.formEdit = false
      this.formStatus = "create"
      this.$nextTick(() => {
        this.$refs.depRuleForm.clearValidate()
      })
      this.doctorList.sysOrgId = this.userInfo.sysOrganizationId
      this.doctorList.deptId = this.userHisDeptId
      //查询医护人员
      const res = await medicalStaffList(this.doctorList)
      console.log(res)
      if (res.code === "1000") {
        this.doctorOptions = res.data
      }
    },
    // 删除
    deleteHandle(data) {
      console.log(data)
      this.isGetNode = false
      if (data.hasChildrenId) {
        this.$message({
          message: "该科室有下级科室，请先删除下级！",
          type: "warning",
          duration: 2000
        })
        return
      } else {
        this.$confirm("确认删除当前记录吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          closeOnClickModal: false
        }).then(() => {
          Delete(data.id).then(res => {
            console.log(res)
            this.getMenuList()
            this.cancel()
            success()
          })
        })
      }
    },
    // 取消按钮
    cancel() {
      this.resetForm()
      this.addStatus = false
      this.formEdit = true
      this.formStatus = ""
      // this.$refs.depRuleForm.resetFields()
    },
    // 重置表单
    resetForm() {
      this.depForm = Object.assign({}, defaultDic)
    },
    // 提交新增
    create() {
      this.formEdit = true
      this.$refs.depRuleForm.validate(async valid => {
        if (!valid) {
          this.formEdit = false
          return false
        } else {
          const res = await addDeptDic(this.depForm)
          // console.log(res)
          if (res.code === "1000") {
            this.formEdit = true
            this.cancel()
            this.getMenuList()
            success()
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .table-item {
  height: 100%;
  margin-right: 0 !important;
}
.depForm {
  height: 100%;
  .el-form {
    width: 80%;
    height: 100%;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    .top {
      flex: 1;
      padding: 20px 0;
      overflow: hidden;
      overflow-y: auto;
      padding-right: 30px;
    }
    .bottom {
      .el-form-item {
        height: 80px;
        /deep/ .el-form-item__content {
          padding-top: 30px;
        }
      }
    }
  }
}
</style>
